package com.neusoft.neuiotms.dcam.fixed.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcam.fixed.model.QStorehouse;
import com.neusoft.neuiotms.dcam.fixed.model.Storehouse;
import com.neusoft.neuiotms.dcam.fixed.model.enums.StorehouseStatus;
import com.neusoft.neuiotms.dcam.fixed.repository.CustomizedStorehouseRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedStorehouseRepositoryImpl extends AbstractRepository implements CustomizedStorehouseRepository {

    @Override
    public Page<Storehouse> search(final Pageable pageable, final Searchable searchable) {
        final QStorehouse qStorehouse = QStorehouse.storehouse;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Storehouse> query = this.query().selectFrom(qStorehouse);
        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return Storehouse.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QStorehouse qStorehouse = QStorehouse.storehouse;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.or(super.containsStr(qStorehouse.name, searchable, "name"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.or(super.containsStr(qStorehouse.location.name, searchable, "name"));
            where.or(super.containsStr(qStorehouse.location.code, searchable, "name"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("status"))) {
            where.and(super.equalsEnum(qStorehouse.status, searchable, "status",
                    value -> StorehouseStatus.valueOf(value)));
        }

        return where;
    }

}
